<template>
    <div class="content">
      <div class="content-head">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="createRole_btn">创建角色</el-button>
      </div>
      <div class="content-table">
        <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" height="100%">
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column prop="roleName" label="角色名称" width="120"></el-table-column>
            <el-table-column prop="roleDes" label="角色描述" width="270"></el-table-column>
            <el-table-column prop="" label="角色权限" width="">
              <template slot-scope="{ row, $index }">
                <el-tag v-for="item,index in row.permissionNameList" :key="index" style="margin:0 5px 3px 0;">{{ item.name }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdDate" label="创建时间" width="150"></el-table-column>
            <el-table-column prop="" label="操作" width="150"  fixed="right">
              <template slot-scope="{ row, $index }">
                  <el-button type="text" @click="edit_btn(row)" :disabled="row.interned">编辑</el-button>
                  <el-button type="text" @click="examine_btn(row)">查看</el-button>
                  <el-popconfirm title="确定删除该角色吗？" @onConfirm="delete_btn(row)">
                    <el-button type="text" slot="reference" style="margin-left:10px;" :disabled="row.interned">删除</el-button>
                  </el-popconfirm>
              </template>
            </el-table-column>
        </el-table>
      </div>
      <div class="content-footer">
        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,40,50]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
      </div>
      <!-- dialog -->
      <div v-if="dialogVisible">
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" @close="dialogCancel_btn" class="dialog-content">
          <el-form label-position="right" label-width="80px" ref="dialogForm" :model="dialogForm" :rules="dialogFormRules" size="small" :disabled="dialogState === 1" style="width:80%;">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="dialogForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="dialogForm.roleDesc"></el-input>
            </el-form-item>
            <el-form-item label="角色权限" prop="rolePermissionList">
              <el-checkbox-group v-model="dialogForm.rolePermissionList">
                <el-checkbox v-for="item,index in primissionNameList" :key="index" :label="item.name"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="创建时间" v-if="dialogState !== 0">
              <el-input v-model="dialogForm.createdDate" :disabled="dialogState === 2"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer" v-if="dialogState !== 1">
            <el-button size="small" @click="dialogCancel_btn">取 消</el-button>
            <el-button type="primary" size="small" @click="dialogConfirm_btn">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </template>
  
  <script>
  import { permissionRoutes } from "@/utils/tools.js";
  import { reqRoleList, reqCreateRole, reqUpdateRole, reqDelRole } from "@/api/user.js";
  export default {
    data() {
      const validate1 = (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入角色名称'));
        } else if(value.trim().length < 2){
          callback(new Error("角色名称不能少于两个字符"));
        } else {
          callback();
        }
      };
      const validate2 = (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入角色描述信息'));
        } else if(value.trim().length < 2){
          callback(new Error("角色描述信息不能少于两个字符"));
        } else {
          callback();
        }
      };
      const validate3 = (rule, value, callback) => {
        console.log(value);
        if (value.length === 0) {
          callback(new Error('请给角色添加至少一个权限'));
        } else {
          callback();
        }
      };
      return {
        tableData:[],
        currentPage:1,
        pageSize:10,
        total:0,
        dialogVisible:false,  //dialog弹出层
        dialogForm:{
          id:"",
          roleName:"",
          roleDesc:"",
          rolePermissionList:[],
          createdDate:""
        },
        dialogFormRules:{
          roleName: [{ validator: validate1, trigger: 'blur' }],
          roleDesc: [{ validator: validate2, trigger: 'blur' }],
          rolePermissionList: [{ require:true, validator: validate3, trigger: 'change' }],
        },
        dialogState:0,  //dialog弹出层状态 0-添加 1-查看 2-编辑
        tableLoading:false,
        primissionNameList:[]  //权限list
      }
    },
    computed:{
      dialogTitle(){
        let title = "";
        if(this.dialogState === 0){
          title = "添加角色";
        } else if (this.dialogState === 1){
          title = "查看角色";
        } else if (this.dialogState === 2){
          title = "编辑角色";
        }
        return title;
      }
    },
    mounted(){
      this.dealPermissionNameList();
      this.getRoleList();
    },
    methods:{
      //分页获取角色列表信息
      getRoleList() {
        const page = this.currentPage;
        const size = this.pageSize;
        this.tableLoading = true;
        reqRoleList(page,size).then(response => {
          if(response.data.code === 200){
            const list = response.data.data.content;
            for(let i = 0; i < list.length; i ++){
              const menuIds = list[i].menuIds;
              let tmp = this.primissionNameList.filter(item => {
                if(menuIds.includes(item.id)){
                  return true;
                }
                return false;
              })
              list[i].permissionNameList = tmp;
            }
            this.tableData = list;
            this.total = response.data.data.totalElements;
          }
          console.log("获取角色列表api",response);
          this.tableLoading = false;
        }).catch(error => {
          this.$message({type:"error",message:"获取角色列表信息失败"});
          this.tableLoading = false;
        })
      },
      //创建角色
      createRole_btn(){
        this.dialogState = 0;
        this.dialogVisible = true;
      },
      //分页器
      handleCurrentChange(curPage){
        this.currentPage = curPage;
        //重新获取数据
        this.getRoleList();
      },
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        //重新获取数据
        this.getRoleList();
      },
      //表格相关的按钮
      edit_btn(row){
        this.dialogState = 2;
        this.dialogVisible = true;
        const { id, roleName, roleDes, menuIds, permissionNameList, createdDate, menus } = row;
        this.dialogForm.id = id;
        this.dialogForm.roleName = roleName;
        this.dialogForm.roleDesc = roleDes;
        this.dialogForm.rolePermissionList = permissionNameList.map(item => item.name);
        this.dialogForm.createdDate = createdDate;
      },
      examine_btn(row){
        this.dialogState = 1;
        this.dialogVisible = true;
        const { id, roleName, roleDes, menuIds, permissionNameList, createdDate, menus } = row;
        this.dialogForm.id = id;
        this.dialogForm.roleName = roleName;
        this.dialogForm.roleDesc = roleDes;
        this.dialogForm.rolePermissionList = permissionNameList.map(item => item.name);
        this.dialogForm.createdDate = createdDate;
      },
      delete_btn(row){
        const roleId = row.id;
        reqDelRole(roleId).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"角色删除成功"});
            //更新列表
            this.getRoleList();
          }
          console.log("删除角色api",response);
        }).catch(error => {
          this.$message({type:"error",message:"删除失败:" + error.response.data.message});
        })
      },
      //dialog相关按钮
      dialogCancel_btn(){
        this.dialogState = 0;
        this.dialogVisible = false;
        this.dialogForm.id = "";
        this.dialogForm.roleName = "";
        this.dialogForm.roleDesc = "";
        this.dialogForm.rolePermissionList = [];
        this.dialogForm.createdDate = "";
      },
      dialogConfirm_btn(){
        let isValidate = false;
        this.$refs.dialogForm.validate((validate) => {
          if(!validate){
            this.$message({type:"info",message:"将表单项填写完整"});
            isValidate = false;
            return;
          } else {
            isValidate = true;
          }
        })
        if(!isValidate) return;
        const permissionList = this.primissionNameList;
        const {roleName, roleDesc, rolePermissionList, id} = this.dialogForm;
        let permissionIds = permissionList.filter((item,index) => {
          if(rolePermissionList.includes(item.name)){
            return true;
          }
          return false;
        }).map(item => item.id);
        const params = {roleName,roleDesc,permissionIds};
        if(this.dialogState === 0){
          //添加
          reqCreateRole(params).then(response => {
            if(response.data.code === 200){
              this.$message({type:"success",message:"角色创建成功"});
              //关闭dialog
              this.dialogCancel_btn();
              //列表刷新
              this.getRoleList();
            }
            console.log("角色创建api",response);
          }).catch(error => {
            this.$message({type:"error",message:"角色创建失败" + error.response.data.message});
          })
        } else if(this.dialogState === 2){
          params.id = id;
          reqUpdateRole(params).then(response => {
            if(response.data.code === 200){
              this.$message({type:"success",message:"角色更新成功"});
              //关闭dialog
              this.dialogCancel_btn();
              //列表刷新
              this.getRoleList();
            }
            console.log("角色更新api",response);
          }).catch(error => {
            this.$message({type:"error",message:"角色更新失败" + error.response.data.message});
          })
        }
      },
      dealPermissionNameList(){
        this.primissionNameList = permissionRoutes.map(item => {
          return {id:item.id,name:item.name};
        })
      }
    }
  }
  </script>
  
  <style lang='scss' scoped>
  .content{
    width: 100%;
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
    padding: 10px 20px;
    box-sizing: border-box;
  
    .content-head{
      height: 10%;
    }
    .content-table{
      height: 80%;
      margin: 10px 0;
    }
    .content-footer{
      height: 10%;
      display: flex;
      justify-content: flex-end;
    }
  }
  </style>